﻿using UnityEngine;
using UnityEngine.UI;

public abstract class UpgradeBtn : MonoBehaviour
{
    public Text lvText;
    public Text priceText;

    public GameObject mask;

    public  MGameUser gameUser
    {
        get
        {
            if (MGame.instance)
                return MGame.instance.MUser;
            else
                return GetComponentInParent<MBattleSceneController>().gameUser;
        }
    }


    public abstract void OnUpgradeJumpPower();
}

public class SpeedUpgradeBtn : UpgradeBtn
{
    void Start()
    {
        InitUI();
    }

    void InitUI()
    {
        int nextLv = gameUser.belikeNum + 1;
        this.lvText.text = "Level " + nextLv;
        int price = MLocalUserData.GetUpgradePrice(nextLv);
        this.priceText.text = price.ToString();

        priceText.transform.parent.gameObject.SetActive(price <= gameUser.coin);
        mask.SetActive(gameUser.coin < price);
    }

    public override void OnUpgradeJumpPower()
    {
        int nextLv = gameUser.belikeNum + 1;
        int price = MLocalUserData.GetUpgradePrice(nextLv);

        if (gameUser.coin >= price)
        {
            OnUpgrade();
        }
        else
        { 
            AudioController.instance.PauseMusic();

            Game.Instance.adManager.PlayVideoAd(() =>
                {
                    AudioController.instance.ResumeMusic();
                    OnUpgrade(true);
                }
                , () =>
                {
                    AudioController.instance.ResumeMusic();
                }, (err) =>
                {
                    AudioController.instance.ResumeMusic();
                    Game.Instance.ShowNoticePanel(err);
                });
        }
    }

    void OnUpgrade(bool ad = false)
    {
        float oldAddJP = MLocalUserData.GetAddSpeedWithLevel(gameUser.belikeNum);

        int newLv = gameUser.UpgradeSpeedLevel(ad);

        InitUI();

        float newAddJP = MLocalUserData.GetAddSpeedWithLevel(newLv);

        MBattleMainUI battleUI = GetComponentInParent<MBattleMainUI>();
        if (newAddJP - oldAddJP > .0001f)
        {
            UnityEngine.GameObject hitFXPref =
                ResourceManager.Load<UnityEngine.GameObject>(GameResourceManager.upgradeFxPath);

            if (hitFXPref)
            {
                var fx = UnityEngine.GameObject.Instantiate(hitFXPref);
                fx.AddComponent<DelayDestroy>();
                fx.transform.position = battleUI.MBattleController.me.transform.position + new Vector3(0, 0.15f, 0);
            }
        }

        battleUI.MBattleController.me.speed += newAddJP - oldAddJP;
        battleUI.MBattleController.me.curMoveSpeed = battleUI.MBattleController.me.speed;
    }
    
    void Update()
    {
        if (Time.frameCount % 60 == 0)
        {
            InitUI();
        }
    }
}


